import {ref} from 'vue';

export function useWebSocket(url, receiveCallback) {
    const socket = ref(null);
    const error = ref(null);
    const readyState = ref(-1);

    let retry = true; //重连开关
    console.debug("load WebSocket ...")

    // 连接 WebSocket
    const connect = (token) => {
        if (readyState.value !== -1 && readyState.value !== WebSocket.CLOSED) {
            return;
        }
        if (!token){
            console.warn("token为空，无法连接websocket");
            return;
        }

        socket.value = new WebSocket(`${url}?token=${token}`);

        socket.value.onopen = () => {
            readyState.value = socket.value.readyState;
            console.log('WebSocket connected');
        };

        socket.value.onmessage = (event) => {
            console.debug("WebSocket receive: ", event.data);

            if (event.data.startsWith("{") && event.data.endsWith("}")) {
                //{"message":{"id":"25482703-6b073bb3af1e","sender":"chid_aafd79ff6b80","receiver":"chid_50037860dc3f","createTime":"2022-12-03 10:27:12","state":0,"toCustomer":false,"topicId":null,"dataType":"TEXT","localId":"0vgcqoi2yk3p","content":"烦烦烦烦烦烦","voice":null,"status":"CREATE","convId":43,"urlRef":false,"type":0,"stale":false,"transferred":false},"msgModel":"MESSAGE","extend":null}
                const chatData = JSON.parse(event.data);

                if (receiveCallback){
                    receiveCallback(chatData);
                }
            }
        };

        socket.value.onerror = (event) => {
            error.value = event;
            console.error('WebSocket error:', event);
        };

        socket.value.onclose = (event) => {
            readyState.value = event.target.readyState;
            console.log('WebSocket closed: event', event.type);

            // 自动重连
            if (retry){
                console.log("尝试重连 WebSocket ....")
                setTimeout(() => connect(token), 3000);
            }
        };
    };

    // 发送消息
    const send = (data) => {
        if (socket.value && socket.value.readyState === WebSocket.OPEN) {
            socket.value.send(JSON.stringify(data));
        }
    };


    const disconnect = () => {
        retry = false;
        if (socket.value) {
            socket.value.close();
            socket.value = null;
        }
    };

    return {
        // error,
        send,
        connect,
        disconnect,
    };
}